package com.qg.base.utils;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class BatchUtil {
    /**
     * 分批做某事
     *
     * @param list      总list
     * @param batchSize 每批大小
     * @param <T>       泛型
     */
    public static <T> Doing<T> with(List<T> list, int batchSize) {
        List<List<T>> split = split(list, batchSize);
        return new Doing<>(split);
    }



    public static <T> List<List<T>> split(List<T> list, int batchSize) {
        int pageSize = list.size() % batchSize == 0 ? (list.size() / batchSize) : (list.size() / batchSize) + 1;
        return IntStream.range(0, pageSize).mapToObj(currentPage -> list.stream().skip((long) currentPage * batchSize).limit(batchSize).collect(Collectors.toList())).collect(Collectors.toList());
    }

    public static class Doing<T> {
        private final List<List<T>> list;
        private ThreadPoolExecutor threadPoolExecutor;

        public Doing(List<List<T>> list) {
            this.list = list;
        }


        public void toDo(Consumer<List<T>> doing) {
             list.forEach(doing);
        }

        public List<T> toDoReturn(Function<List<List<T>>, List<T>> doing) {
            return doing.apply(list);
        }
    }
}
